package com.hundsun.aitest.util;
import com.hundsun.aitest.model.ai.ChatRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.interfaces.PBEKey;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
public class HttpUtils {

    private static final CloseableHttpClient httpClient = HttpClients.createDefault();

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 发送 GET 请求
     *
     * @param url 请求的 URL
     * @return 返回的字符串响应
     */
    public static String sendGetRequest(String url) {
        HttpGet httpGet = new HttpGet(url);
        return executeRequest(httpGet);
    }

    /**
     * 发送 GET 请求
     *
     * @param url 请求的 URL
     * @return 返回的字符串响应
     */
    public static String sendGetRequestTwo(String url, Map<String, String> headers, Map<String, Object> params) {
        String queryString = params.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        url = url + "?" + queryString;
        HttpGet httpGet = new HttpGet(url);
        setCustomHeaders(httpGet, headers);
        return executeRequest(httpGet);
    }

    /**
     * 发送 POST 请求
     *
     * @param url 请求的 URL
     * @param body 请求正文（JSON）
     * @return 返回的字符串响应
     */
    public static String sendPostJsonRequest(String url, String body, Map<String, String> headers) {
        HttpPost httpPost = new HttpPost(url);
        try {
            httpPost.setEntity(new StringEntity(body, "UTF-8"));
            httpPost.setHeader("Content-type", "application/json");
            setCustomHeaders(httpPost, headers);

        } catch (Exception e) {
            log.error("sendPostJsonRequest失败，url={},body={},headers={}",url,body,headers,e);
            throw new RuntimeException("Error setting request entity", e);
        }
        return executeRequest(httpPost);
    }

    /**
     * 发送 POST 请求
     *
     * @param url 请求的 URL
     * @param params 请求参数（key-value 形式）
     * @return 返回的字符串响应
     */
    public static String sendPostFormUrlEncodedRequest(String url, Map<String, String> params,Map<String, String> headers) {
        HttpPost httpPost = new HttpPost(url);
        try {
            List<BasicNameValuePair> formParams = convertToBasicNameValuePairs(params);
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8));
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            setCustomHeaders(httpPost, headers);

        } catch (Exception e) {
            log.error("sendPostFormUrlEncodedRequest，url={},params={},headers={}",url,params,headers,e);
            throw new RuntimeException("Error setting request entity", e);
        }
        return executeRequest(httpPost);
    }

    /**
     * 将 Map 转换为 BasicNameValuePair 列表
     *
     * @param params Map 参数
     * @return BasicNameValuePair 列表
     */
    private static List<BasicNameValuePair> convertToBasicNameValuePairs(Map<String, String> params) {
        List<BasicNameValuePair> formParams = new ArrayList<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return formParams;
    }

    /**
     * 执行 HTTP 请求
     *
     * @param request 请求对象
     * @return 返回的字符串响应
     */
    private static String executeRequest(HttpRequestBase request) {
        try {
            HttpResponse response = httpClient.execute(request);
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (IOException e) {
            log.error("executeRequest 异常，request={}",request,e);
            throw new RuntimeException("Error executing HTTP request", e);
        }
    }

    /**
     * 设置自定义请求头
     *
     * @param request 请求对象
     * @param headers 请求头 Map
     */
    private static void setCustomHeaders(HttpRequestBase request, Map<String, String> headers) {
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                request.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * 关闭 HttpClient 实例
     */
    public static void shutdown() {
        try {
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Map<String, String> convertObjectToMap(ChatRequest chatRequest) {
        Map<String, String> params = new HashMap<>();
        params.put("model", chatRequest.getModel());
        chatRequest.getMessages().forEach(message -> {
            params.put("messages.role", message.getRole());
            params.put("messages.content", message.getContent());
        });
        params.put("max_tokens", chatRequest.getMaxTokens());
        params.put("user", chatRequest.getUser());
        return params;
    }
}